import axios from 'axios'
import { Message } from 'element-ui'
// create an axios instance
// let env = process.env.NODE_ENV
/**
 * 配置全局baseurl
 * proxyLocal 与 prod 和 vueconfig文件中 devserve proxyTarget填入合适的对应ip或域名配合使用
 * 其它可直接使用
 */

const BASEURL = {
  'test': 'http://172.18.70.102:9002/recruit-api', // 测试环境
  'prod': 'https://mba-know-ledge.ministudy.com/recruit-api', // 线上环境
  'proxyLocal': '/recruit-api', // 代理本地
  'chj': 'http://172.18.0.244:8082/recruit-api', // 陈海建
  'zy': 'http://172.18.5.7:8082/recruit-api' // 张勇
}
let baseURL = BASEURL.zy

if (process.env.NODE_ENV === 'test') {
  baseURL = BASEURL.test
}
const service = axios.create({
  baseURL,
  timeout: 50000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    config.headers['token'] = sessionStorage.getItem('token')
    config.headers['type'] = 'h5'
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    if (response.data.code === 401) {
      Message({
        message: '页面已失效，或停留时间过长，请刷新重试',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(response.data.msg)
    } else {
      return response
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
